package com.ssky.bean.validator.factory;

import com.ssky.bean.validator.ValidatorBuilder;
import com.ssky.bean.validator.core.exception.VldException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @Author: ssky
 * @Date: 2021/07/18
 * @Description:
 */
public class RuleCheckerFactory {
    private static final Logger L = LoggerFactory.getLogger(ValidatorBuilder.class);

    public static final Map<String, Class<?>> CheckerClassMap = new HashMap<>();

    /**
     * 请使用classpath:匹配单个properties文件资源，如果需要匹配多个资源，请调用多次；需要注意，如果key重复会覆盖。
     *
     * @param localtionPattern 类路径加载资源，classpath:匹配单个资源方式。
     */
    public static void load(String localtionPattern) throws VldException {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = null;
        try {
            resources = resolver.getResources(localtionPattern);
        } catch (IOException e1) {
            L.error("RuleCheckerFactory --> load Scan checker list  = " + localtionPattern + " occur error-->", e1);
            throw new VldException(e1.getMessage());
        }
        if (resources == null || resources.length == 0) {
            throw new VldException("Resource(" + localtionPattern + ") not found");
        }
        Properties properties = new Properties();
        try (InputStream is = resources[0].getInputStream();) {
            properties.load(is);
        } catch (Exception e) {
            L.error("RuleCheckerFactory load(" + localtionPattern + ") occured exception -->", e);
            throw new VldException(e.getMessage());
        }

        Set<String> set = properties.stringPropertyNames();
        for (String key : set) {
            //使用getProperty获取值
            String value = properties.getProperty(key);
            Class<?> clazz;
            try {
                clazz = Class.forName(value);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                throw new VldException(e.getMessage());
            }
            CheckerClassMap.put(key, clazz);
        }
        properties = null;
    }

    public static Class getCheckerClass(String aliasKey) {
        return CheckerClassMap.get(aliasKey);
    }

    /**
     * 注册，重名会被覆盖
     *
     * @param aliasKey
     * @param checkerClass
     */
    public static void addChcker(String aliasKey, Class<?> checkerClass) {
        CheckerClassMap.put(aliasKey, checkerClass);
    }


    /**
     * @param aliasKey
     */
    public static void remove(String aliasKey) {
        CheckerClassMap.remove(aliasKey);
    }
}
